package com.wk.springboot.annotation;

import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * description: 这里是Calculator的CGLIB代理
 * date 2020-12-05 19:49
 *
 * @author Administrator
 * @version 1.0
 */
public class CglibProxy implements MethodInterceptor {


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        //获取LogAnnotation
        LogEnum logEnum = LogEnum.PARAMS;
        LogAnnotation logAnnotation = o.getClass().getAnnotation(LogAnnotation.class);
        if(logAnnotation != null){
            String value = logAnnotation.value();
            System.out.println(value);
            logEnum = logAnnotation.method();
            if (logEnum == LogEnum.PARAMS) {
                System.out.println(method.getName()+"方法的参数为："+ Arrays.asList(objects));
            }
        }
        //注意，这里是invokeSuper，不是invoke。invoke会出现递归调用
        Object object = null;
        try {
            object = methodProxy.invokeSuper(o,objects);
            if (logEnum == LogEnum.RETURN){
                System.out.println(method.getName()+"计算结果 = " + object);
            }
        } catch (ArithmeticException ae) {
            if(logEnum == LogEnum.THROW){
                System.out.println(method.getName()+"计算异常 = " + ae);
            }else {
                throw new Exception(ae);
            }
        }
        return object;

    }
}
